package com.zfei.gfb.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.generator.UUIDGenerator;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.GlobalHeaders;
import cn.hutool.http.Header;
import cn.hutool.http.HttpUtil;
import com.zfei.gfb.GfbService;
import com.zfei.gfb.bean.Const;
import com.zfei.gfb.bean.StatusException;
import com.zfei.gfb.dao.*;
import com.zfei.gfb.model.*;
import com.zfei.gfb.util.Beans;
import com.zfei.gfb.util.Gsons;
import com.zfei.gfb.util.Now;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


@Component
public class GfbServiceImpl implements GfbService {

    @Value("${score.url}")
    private String scoreUrl ="https://azalea-tech.com/dev/daicun";

    private final static String appKey = "o5i7oij4e6tr6dkb0k5fhl5g";
    private static final Logger logger = LoggerFactory.getLogger(GfbServiceImpl.class);


    @Resource
    private GfbVillagerMapper gfbVillagerMapper;

    @Resource
    private GfbGuestMapper gfbGuestMapper;

    @Resource
    private GfbCompanyMapper gfbCompanyMapper;

    @Resource
    private GfbOrderMapper gfbOrderMapper;

    @Resource
    private GfbGoodsMapper gfbGoodsMapper;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public GfbGuest addGuest(String openId) {
        GfbGuest guest = new GfbGuest();
        guest.setOpenId(openId);
        guest.setCreateTime(Now.millis());
        guest.setUpdateTime(Now.millis());
        guest.setCntime(DateUtil.now());
        guest.setLastTime(Now.millis());
        gfbGuestMapper.insertSelective(guest);
        return guest;
    }

    @Override
    public GfbVillager addVillager(String uuid, String phone, String name, String idCard, Integer sourceUserId, String villagerName, String town, Integer naturalVillageId, String naturalVillageName, String groupNumber, String address) {
        //认证通过
        GfbVillager villager = new GfbVillager();
        villager.setName(name);
        villager.setPhone(phone);
        villager.setIdCard(idCard);
        villager.setAddress(address);
        villager.setVillagerName(villagerName);
        villager.setTown(town);
        villager.setSourceUserId(sourceUserId);
        villager.setExt(uuid);
        villager.setCreateTime(Now.millis());
        villager.setUpdateTime(Now.millis());
        villager.setCntime(DateUtil.now());
        villager.setNaturalVillageId(naturalVillageId);
        villager.setNaturalVillageName(naturalVillageName);
        villager.setGroupNumber(groupNumber);
        gfbVillagerMapper.insertSelective(villager);
        return villager;
    }

    @Override
    public GfbCompany addCompany(String phone) {

        GfbCompany company = new GfbCompany();
        company.setPhone(phone);
        company.setAudit(Const.COMPANY_UNAUTHORIZED);
        company.setStatus(Const.STATUS_ON);
        company.setCreateTime(Now.millis());
        company.setCntime(DateUtil.now());
        company.setUpdateTime(Now.millis());
        gfbCompanyMapper.insertSelective(company);
        return company;
    }

    @Override
    public int balance(Integer userId) {

        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("userId", userId.toString());

        GlobalHeaders.INSTANCE.header("sign", getSign(paramMap));

        Map<String, Object> map1 = new HashMap<>(paramMap);
        String result = HttpUtil.get(scoreUrl + "/api/external/users/point/query", map1);

        return Beans.getJsonData(result, null, true).getAsInt();

    }


    @Override
    public GfbVillager confirm(String uuid) {
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("userUuid", uuid);
        logger.info(getSign(paramMap));

        GlobalHeaders.INSTANCE.header("sign", getSign(paramMap));
        Map<String, Object> map1 = new HashMap<>(paramMap);
        String result = HttpUtil.get(scoreUrl + "/api/external/users/verification", map1);
        logger.info("url ={}", scoreUrl + "/api/external/users/verification");
        logger.info("result ={}", result);
        try {
            Gsons.parseJsonObject(result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new StatusException("积分系统返回出错,error=" + e.getMessage());
        }

        GfbVillager villager = new GfbVillager();
        Integer userId = Beans.getJsonData(result, "userId").getAsInt();
        String realName = Beans.getJsonData(result, "realName").getAsString();
        String phone = Beans.getJsonData(result, "phone").getAsString();
        String idNumber = Beans.getJsonData(result, "idNumber").getAsString();
        String villageName = Beans.getJsonData(result, "villageName").getAsString();

        String town = Beans.getJsonData(result, "town").getAsString();
        Integer naturalVillageId = Beans.getJsonData(result, "naturalVillageId").getAsInt();
        String naturalVillageName = Beans.getJsonData(result, "naturalVillageName").getAsString();
        String groupNumber = Beans.getJsonData(result, "groupNumber").getAsString();
        String address = Beans.getJsonData(result, "address").getAsString();

        villager.setName(realName);
        villager.setVillagerName(villageName);
        villager.setPhone(phone);
        villager.setIdCard(idNumber);
        villager.setSourceUserId(userId);
        villager.setTown(town);
        villager.setNaturalVillageId(naturalVillageId);
        villager.setNaturalVillageName(naturalVillageName);
        villager.setGroupNumber(groupNumber);
        villager.setAddress(address);

        return villager;
    }

    @Override
    @Transactional
    public GfbOrder order(GfbVillager villager, GfbGoods goods) {

        GfbOrder record = new GfbOrder();
        //物品信息
        record.setOrderId(new UUIDGenerator().next());
        record.setGoodsId(goods.getId());
        record.setGoodsName(goods.getName());
        record.setUserId(villager.getId());
        record.setPrice(goods.getPrice());
        record.setGoodsImages(goods.getImages());
        //兑换信息-村民
        record.setAddress(goods.getAddress());
        record.setLinkName(villager.getName());
        record.setPhone(villager.getPhone());

        record.setStatus(Const.GOOD_DEAL);
        record.setCreateTime(Now.millis());
        record.setUpdateTime(Now.millis());
        record.setCntime(DateUtil.now());

        gfbOrderMapper.insertSelective(record);

        goods.setStatus(Const.GOOD_DEAL);
        gfbGoodsMapper.updateByPrimaryKeySelective(goods);

        String sql = "INSERT INTO `gfb_workpoint` (`type`, `user_id`, `order_id`, `num`, `create_time`) VALUES (?, ?, ?,?,?)";
        Object[] args = new Object[]{1, villager.getId(), record.getId(), goods.getPrice(), Now.millis()};
        jdbcTemplate.update(sql, args);
        return record;
    }

    @Override
    @Transactional
    public void writeOffOrder(GfbOrder gfbOrder, GfbGoods goods) {
        gfbOrder.setStatus(Const.GOOD_COMPLETED);
        gfbOrderMapper.updateByPrimaryKeySelective(gfbOrder);
        goods.setStatus(Const.GOOD_COMPLETED);
        gfbGoodsMapper.updateByPrimaryKeySelective(goods);

        try {
            String sql = "INSERT INTO `gfb_workpoint` (`type`, `user_id`, `order_id`, `num`, `create_time`) VALUES (?, ?, ?,?,?)";
            Object[] args = new Object[]{2, goods.getUserId(), gfbOrder.getId(), gfbOrder.getPrice(), Now.millis()};
            jdbcTemplate.update(sql, args);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

    }

    @Override
    public void reduce(Integer userId, Integer price) {

        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("userId", userId.toString());
        paramMap.put("amount", price.toString());
        paramMap.put("msg", "工分宝购买物品");
        logger.info(getSign(paramMap));

        GlobalHeaders.INSTANCE.header("sign", "JR_IWwxJTsA");
        GlobalHeaders.INSTANCE.header(Header.CONTENT_TYPE, ContentType.JSON.getValue());
        Map<String, Object> map1 = new HashMap<>(paramMap);

        String result = HttpUtil.post(scoreUrl + "/api/external/users/consumption", Gsons.toJson(map1));
        logger.info("url={},params ={}", scoreUrl + "/api/external/users/consumption", Gsons.toJson(map1));
        logger.info("result ={}", result);
    }

    @Override
    public void recharge(Integer userId, Integer price) {
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("userId", userId.toString());
        paramMap.put("amount", price.toString());
        paramMap.put("msg", "工分宝售卖物品");
        logger.info(getSign(paramMap));

        GlobalHeaders.INSTANCE.header("sign", "JR_IWwxJTsA");
        GlobalHeaders.INSTANCE.header(Header.CONTENT_TYPE, ContentType.JSON.getValue());
        Map<String, Object> map1 = new HashMap<>(paramMap);

        String result = HttpUtil.post(scoreUrl + "/api/external/shops/consumption", Gsons.toJson(map1));
        logger.info("url={},params ={}", scoreUrl + "/api/external/shops/consumption", Gsons.toJson(map1));
        logger.info("result ={}", result);
    }

    @Override
    public void updateVillager(GfbVillager realVillager) {
        realVillager.setUpdateTime(Now.millis());
        gfbVillagerMapper.updateByPrimaryKeySelective(realVillager);
    }

    public static void main(String[] args) {
        new GfbServiceImpl().confirm("5293");
    }


    public static String getSign(Map<String, String> paramMap) {
        //获取参数列表
        List<String> parameterList = new ArrayList<>();
        StringBuilder parameterBuilder = new StringBuilder();
        for (String key : paramMap.keySet()) {
            parameterList.add(key + "=" + paramMap.get(key));
        }
        Collections.sort(parameterList);
        for (int i = 0; i < parameterList.size(); i++) {
            if (i > 0) {
                parameterBuilder.append("&");
            }
            parameterBuilder.append(parameterList.get(i));
        }
        //验证签名
        return sigverif(parameterBuilder.toString());

    }

    public static String sigverif(String parameterStr) {

        SecureUtil.des(parameterStr.getBytes());
        return encryptBase64(parameterStr, appKey);
    }


    public static String encryptBase64(String content, String key) {
        return Base64.encodeUrlSafe(SecureUtil.desede(key.getBytes()).encrypt(content));
    }
}
